<?php

/**
 * @Name : 上传资源垃圾回收服务
 * @Function :
 * @Author : Haiwera
 * @Created : 2016-11-08
 * @Copyright : Haiwera.Fiidee.Monda.Cn
 */
namespace admin\service;

use herosphp\core\Loader;

class GcResourceService extends CommonService
{


    public function gc($file, $table, $field, $rid)
    {

        // 查找半小时前所有进行过删除操作的资源
        $gbsh = parent::getItems(array('addtime' => array('<' => date("Y-m-d H:i:s", time(0) - 1800))));
        $ids = array();
        foreach ($gbsh as $k => $v) {

            $t = str_replace(array(' ', '-'), '', ucwords(str_replace('_', ' ', '-' . $v['tb'])));
            $m = Loader::model($t);
            if (is_numeric($v['resourceid'])) {
                $v['resourceid'] = intval($v['resourceid']);
            }
            $w = $m->getItem($v['resourceid'], array($v['field']));
            // 判断资源是否依旧被引用
            if (strpos($w[$v['field']], $v['file']) === false) {
                // 若原记录不再引用该资源 ，则进行删除操作
                if (file_exists(APP_ROOT . $v['file'])) {
                    @unlink(APP_ROOT . $v['file']);
                }
            }
            $ids[] = $v['id'];
        }
        parent::deletes(array('id' => array('$in' => $ids)));

        if (!$rid) {
            if (file_exists(APP_ROOT . $file)) {
                @unlink(APP_ROOT . $file);
            }
            return;
        }
        $data = array(
            'file' => $file,
            'field' => $field,
            'tb' => $table,
            'resourceid' => $rid
        );
        parent::add($data);
    }


}
